package com.example.myapplication.utils;

import android.util.Log;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 联网工具类，统一使用
 * 静态内部类单例模式
 * Created by Administrator on 2018/4/23 0023.
 */

public class RetrofitUtils {


    private final String BASE_URL = "http://api01.bitspaceman.com:8000/";
    private Retrofit mRetrofit;

    private RetrofitUtils() {

        initRetrofit();
    }

    private static class RetrofitUtilsHold {
        private static final RetrofitUtils UTILS = new RetrofitUtils();
    }

    public static RetrofitUtils getInstance() {
        return RetrofitUtilsHold.UTILS;
    }

    private void initRetrofit() {

        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                try {
                    String msg = URLDecoder.decode(message, "utf-8");
                    Log.i("OkHttpInterceptor-----", msg);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    Log.i("OkHttpInterceptor-----", message);
                }
            }
        });
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        /*okhttp默认时间15秒 请求时间较长时，重新设置下  */
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(15, TimeUnit.SECONDS);
        builder.readTimeout(15, TimeUnit.SECONDS);
        builder.writeTimeout(15, TimeUnit.SECONDS);
        builder.retryOnConnectionFailure(true);
        OkHttpClient client = builder.build();
        mRetrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(client)
                .build();
    }

    public <T> T getApiServier(Class<T> reqServer) {
        return mRetrofit.create(reqServer);
    }
}
